home *** CD-ROM | disk | FTP | other *** search
- Path: gail.ripco.com!mambuhl
- From: mambuhl@ripco.com (Martin Ambuhl)
- Newsgroups: comp.lang.c
- Subject: Re: free space malloced t
- Date: 7 Feb 1996 16:40:39 GMT
- Organization: Ripco Communications, Inc.
- Message-ID: <4fakm7$247@gail.ripco.com>
- NNTP-Posting-Host: foley.ripco.com
-
- matmrlx@gsusgi1.gsu.edu (Michael R. Lauer)
- in <4eqf8m$smv@gsusgi1.gsu.edu> asks:
-
- >The general question is: if you malloc space for a pointer with automatic
- >storage, should/must you free that space before leaving that scope?
-
- Only if _you_ allocate the space.
-
- >This seems obvious but it is giving me trouble. In this code:
-
- >{
- > struct dirent *dp;
- > if ((dp = readdir() != NULL)
- ^^^^^^^^^
- OK...since readdir() is not a standard C function, I can't _know_ that
- this is an error, but in the implementations I use, the prototype for
- readdir is
- struct dirent readdir(DIR *dirp);
-
- > {
- > }
- > if (dp) /* this seems to cause a segmentation f
- > free(dp); /* when the enclosing function returns
- >}
-
- _You_ are not allocating the space. Handle the memory you allocate. If
- some other function allocates the space it is responsible for making
- sure its usage is safe.
-
- >So readdir returns a pointer to the dirent structure--it is mallocing the
- >space....
-
- How do you know this? In the implementations that I use, the struct
- dirent is allocated as a member of the DIR (which you omitted in the
- call to readdir()). It is also possible that it is a static struct. If
- your call to readdir() is right for your implementation, this only
- underlines why non-standard C is a problem in comp.lang.c.
-
-
- --
- * Martin Ambuhl net: mambuhl@ripco.com
- * Chicago, IL (USA)
-